package org.hzz.locks;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/developeros/videos-online">Code Repository</a>
 * At 2024/9/7
 * 可重入的自旋锁
 */
public class ReentrantSpinLock extends SpinLock {
    private volatile Thread owner = null;
    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public void lock() {
        if(owner == Thread.currentThread()){
            count.incrementAndGet();
            return;
        }
        super.lock();
        owner = Thread.currentThread();
        count.set(1);
    }

    @Override
    public void unlock() {
        if (owner == Thread.currentThread()){
            int currentCount = count.decrementAndGet();
            if (currentCount == 0){
                owner = null;
                super.unlock();
            }
        }
    }
}
